<template>
  <view class="store-settings">
    <!-- 用户信息 -->
    <view class="user-info">
      <view class="user-info-left">
        <view class="avatar-container" @tap="chooseAvatar">
          <image class="avatar" :src="userAvatar" mode="aspectFit"/>
          <text class="change-avatar"style="width: 50px;height: 50px;">更换头像</text>
        </view>
        <view class="user-details">
          <view class="info-item">
			   <text class="label">Id:</text>
            <text class="label">{{id}}</text>

          </view>
          <view class="info-item">
            <text class="label">昵称:</text>
            <input v-if="isEditing" v-model="nickname" class="input-field" placeholder="请输入昵称"/>
            <text v-else>{{nickname}}</text>
          </view>
          <view class="info-item">
            <text class="label">手机号:</text>
            <input v-if="isEditing" v-model="phone" class="input-field" placeholder="请输入ID"/>
            <text v-else>{{phone}}</text>
          </view>
          <view class="edit-button" @tap="handleEdit">
            {{isEditing ? '保存' : '修改'}}
          </view>
        </view>
      </view>
    </view>
    
	<!-- 底部图片上传区域 -->
	<view class="upload-section">
	  <view class="upload-item" @tap="chooseImage('left')">
	    <image v-if="leftImage" :src="leftImage" mode="aspectFit" class="uploaded-img"/>
	    <view v-else class="upload-placeholder">
	      <text>点击上传图片</text>
	    </view>
	  </view>
	  <view class="upload-item" @tap="chooseImage('right')">
	    <image v-if="rightImage" :src="rightImage" mode="aspectFit" class="uploaded-img"/>
	    <view v-else class="upload-placeholder">
	      <text>点击上传图片</text>
	    </view>
	  </view>
	  <view >
	  </view>
	</view>
	  <!-- <view class="radio-group"> -->
	    <!-- 单选框组 -->
	    <!-- <radio-group @change="radioChange">
	      <label class="radio" v-for="item in items" :key="item.value">
	        <radio :value="item.value" :checked="item.checked">{{ item.name }}</radio>
	      </label>
	    </radio-group>
	  </view> -->
	  <!-- 扫描二维码部分 -->
	 <view>
	    <!-- 定义一个按钮，并绑定点击事件 -->
	    <button @click=" clickScan">请点击此处扫描二维码</button>
	  </view>
	
	
    <!-- 抽奖转盘 -->
    <view class="roulette-section">
      <view class="prize-grid">
        <view 
          v-for="(prize, index) in prizes" 
          :key="index" 
          class="prize-item" 
          :class="{ 'highlight': highlightedIndex === index }"
        >
          <view @tap="handlePrizeClick(index, prize)" class="prize-content">
            <image :src="prize.icon" mode="aspectFit" class="prize-img" />
            <text class="prize-name">{{ prize.name }}</text>
          </view>
        </view>
      </view>
      <!-- 中心按钮 -->
      <button 
        @tap="spinRoulette" 
        class="spin-button"
      >
        点击开始
      </button>
    </view>


  </view>
</template>

<script>

export default {
  data() {
    return {
      userAvatar: '/static/default-avatar.png',
      userId: '10001',
      nickname: '用户昵称',
      isEditing: false,
      prizes: [
        { icon: '/static/logo.png', name: '免单' },
        { icon: '/static/logo.png', name: '外卖券' },
        { icon: '/static/logo.png', name: '神秘奖励' },
        { icon: '/static/logo.png', name: '外卖会员' },
        { icon: '', name: '' }, // 中间项
        { icon: '/static/logo.png', name: '随机红包' },
        { icon: '/static/logo.png', name: '最高红包' },
        { icon: '/static/logo.png', name: '最低红包' },
        { icon: '/static/logo.png', name: '点击图标设置奖项' }
      ],
	  // items: [
	  //         { name: '美团', value: '美团', checked: true },
	  //         { name: '饿了么', value: '饿了么', checked: false },
	  //         { name: '自定义', value: '自定义', checked: false }
	  //       ],
      highlightedIndex: null,
      isSpinning: false,
      spinSequence: [],
      spinInterval: null,
      submitPageSetting: 'default',
      lotteryOrderSetting: 'random', // 默认为随机
      maxSubmissionTimeHours: 12,
      dailySubmissionsLimit: 2,
      modificationEnabled: false,
      leftImage: '',
      rightImage: '',
	  id:1,
	  phone:0,
	  storeId:1,
	  status:1,
	  platform:'',
	  accessToken: '',
    };
  },
  

  onLoad(options) {
	  this.id=options.status
	  console.log(this.id)
  	// 发送 code 和用户信息到服务器进行绑定
  	uni.request({
  		url: 'http://zhaoyang.nat300.top/user/select', // 替换为你的服务器地址
  		method: 'POST',
  		data: {
  			id:this.id
  		},
  		header: {
  			'content-type': 'application/json' // 设置请求头，默认值
  		},
  		success: (res) => {
  				this.id = res.data.id
  				console.log('请求成功', res); // 后端返回的数据
  				if (res.statusCode === 200 && res.data != 0) {
  					this.userId = this.id;
					this.nickname =res.data.nickname;
					this.phone = res.data.phone;
					this.userAvatar =res.data.avatar;

  				} else {
  					uni.showToast({
  						title: '绑定失败',
  						icon: 'none',
  					});
  				}
  		
  			},
  			fail(err) {
  				console.error('请求失败', err);
  			}
  	});
  },
  methods: {
	    // 点击扫一扫
	       clickScan() {
	         // 使用uniapp提供扫码api
	         uni.scanCode({
	           scanType: ['qrCode'],
	          // 扫码成功后的回调
	           success: (res) => {
			 console.log(res.result)
	           // res中包含二维码中的信息，其中就有网络链接
	           // 使用navigateTo跳转，并且携带参数，参数为二维码中的链接
			  const resultData = JSON.parse(res.result); // 解析JSON字符串 
			  this.platform = resultData.platform; // 访问 platform 属性
			   this.storeId = resultData.storeId; // 访问 storeId 属性 
			   console.log("storeId: ", this.storeId); 
			   console.log("platform: ", this.platform);
	           }
	         })
	       },

	       // 刷新 access_token 的方法
	       refreshAccessToken() {
	         // 调用 wx.login 获取 code
	         wx.login({
	           success: function(res) {
	             if (res.code) {
	               // 发起网络请求获取新的 access_token
	               wx.request({
	                 url: 'https://your-server.com/get-access-token',
	                 data: {
	                   code: res.code
	                 },
	                 success: function(res) {
	                   // 更新 access_token
	                   const newAccessToken = res.data.access_token;
	                   // 存储新的 access_token 到本地存储
	                   wx.setStorageSync('access_token', newAccessToken);
	                   this.accessToken = newAccessToken;
	                 }
	               });
	             } else {
	               console.error('登录失败！返回code为空');
	             }
	           }
	         });
	       },
	  onConfirm() {
	      this.onLoad(); // 直接重新调用 onLoad
	    },
	   radioChange(evt) {
	        console.log('选中的值:', evt.detail.value);
	        // 更新数据以反映哪个选项被选中
	        this.items.forEach(item => {
	          item.checked = (item.value === evt.detail.value);
	        });
	      },
    handleEdit() {
      if(this.isEditing) {
        if(!this.nickname) {
          uni.showToast({
            title: '请填写完整信息',
            icon: 'none'
          });
          return;
        }
        this.isEditing = false;
      } else {
        this.isEditing = true;
      }
	 uni.request({
	 	url: 'http://zhaoyang.nat300.top/user/update', // 替换为你的服务器地址
	 	method: 'POST',
	 	data: {
	 		id:this.id,
			nickname:this.nickname,
			phone:this.phone,
			avatar:this.userAvatar,
	 	},
	 	header: {
	 		'content-type': 'application/json' // 设置请求头，默认值
	 	},
	 	success: (res) => {
	 			if (res.statusCode === 200 && res.data != 0) {
	 			uni.showToast({
	 				title: '修改成功',
	 				icon: 'none',
	 			});
	 			} else {
	 				uni.showToast({
	 					title: '修改失败',
	 					icon: 'none',
	 				});
	 			}
	 		},
	 		fail(err) {
	 			console.error('请求失败', err);
	 		}
	 });
    },
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.userAvatar = res.tempFilePaths[0];
        }
      });
    },
    chooseImage(position) {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          if(position === 'left') {
            this.leftImage = res.tempFilePaths[0];
          } else {
            this.rightImage = res.tempFilePaths[0];
          }
        }
      });
    },
    spinRoulette() {
		if(this.leftImage=='' || this.rightImage==''){
				uni.showToast({
					title: '请先上传两张截图',
					icon: 'none',
				});	
				return;
		}
      if (this.isSpinning) return;

      this.isSpinning = true;
      this.highlightedIndex = null;

      // 生成旋转序列,但最终结果固定为随机红包(索引5)
      let sequence = [];
      for(let i = 0; i < 20; i++) { // 生成20个随机位置
        sequence.push(Math.floor(Math.random() * 9));
      }
      sequence.push(5); // 最后添加随机红包的位置
      this.spinSequence = sequence.filter(index => index !== 4); // 排除中间格子

      let currentIndex = 0;

      // 开始旋转
      this.spinInterval = setInterval(() => {
        this.highlightedIndex = this.spinSequence[currentIndex];
        currentIndex++;

        // 当到达序列末尾时停止
        if (currentIndex >= this.spinSequence.length) {
          clearInterval(this.spinInterval);
          this.isSpinning = false;
          // 显示中奖弹窗
          uni.showModal({
            title: '恭喜你',
            content: `抽到了 ${this.prizes[this.highlightedIndex].name}`,
            showCancel: false
          });
        }
      }, 200); // 每200毫秒切换一次高亮
	  
	  //发送请求
	  this.upload();
	
    },
	upload(){
		console.log("storeId"+this.storeId);
		console.log("platform"+this.platform);
		uni.request({
			url: 'http://zhaoyang.nat300.top/review/add', // 替换为你的服务器地址
			method: 'POST',
			data: {
				id:this.userId,
				storeId:this.storeId,
				nickname:this.nickname,
				phone:this.phone,
				screen:this.leftImage,
				screenshot:this.rightImage,
				platform:this.platform,
				status:this.status,
			},
			header: {
				'content-type': 'application/json' // 设置请求头，默认值
			},
			success: (res) => {
					if(!res.data){
						uni.showToast({
							title: '已达到单日提交上限',
							icon: 'none',
						});
					}
					console.log('请求成功', res.data); // 后端返回的数
				},
				fail(err) {
					console.error('请求失败', err);
				}
		});
	},
    handlePrizeClick(index, prize) {
      if(index === this.highlightedIndex) {
        uni.showModal({
          title: '提示',
          content: '弹框'
        })
      }
    },
    getSpinSequence() {
      const sequence = [...Array(9).keys()]; // 包含所有格子的索引

      if (this.lotteryOrderSetting === 'random') {
        return sequence.sort(() => Math.random() - 0.5);
      } else { // 'sequential'
        return sequence; // 顺序排列
      }
    },
    enableModification() {
      this.modificationEnabled = true;
    },
    confirmModification() {
      if (this.modificationEnabled) {
        this.modificationEnabled = false;
      }
    }
  }
};
</script>
<style>
	.radio-group {
	  display: flex;
	  justify-content: space-around; /* 横向平均分布 */
	}
	
	.radio {
	  margin-right: 10px; /* 为每个单选按钮添加间距 */
	}
.store-settings {
  padding: 20px;
  font-family: Arial, sans-serif;
}
.user-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
}
.user-info-left {
  display: flex;
  gap: 15px;
}
.avatar-container {
  position: relative;
  cursor: pointer;
}
.avatar {
  width: 80px;
  height: 80px;
  border-radius: 40px;
}
.change-avatar {
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #666;
}
.user-details {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}
.label {
  font-size: 14px;
  color: #666;
  width: 60px;
}
.input-field {
  width: 150px;
  height: 30px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
}
.user-id {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}
.edit-button {
  padding: 5px 15px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  margin-top: 10px;
  width: 80px;
}
.roulette-section {
  position: relative;
  margin-top: 20px;
  text-align: center;
}
.prize-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  justify-content: center;
}
.prize-item {
  width: 100px;
  height: 100px;
  border-radius: 10px;
  background-color: #f9f9f9;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.prize-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
}
.prize-img {
  width: 45px;
  height: 45px;
  margin-bottom: 8px;
  object-fit: contain;
}
.prize-name {
  font-size: 12px;
  color: #333;
  text-align: center;
  line-height: 1.2;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.highlight {
  background-color: yellow;
}
.spin-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
  width: 100px;
  height: 40px;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 16px;
}
.modify-button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 5px 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 14px;
  margin: 4px 2px;
  border-radius: 5px;
}
.modify-button:hover {
  background-color: #45a049;
}
.upload-section {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding: 0 40px;
}
.upload-item {
  width: 120px;
  height: 120px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.upload-placeholder {
  color: #999;
  font-size: 14px;
  text-align: center;
}
.uploaded-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}
</style>